<template>
  <div class="newCourseContainer">
    <div
      class="dialog animated"
      :class="open? 'fadeIn':'fadeOut'"
      v-show="show"
      :style="{visibility: (visible?'visible':'hidden')}"
    >
      <div class="panel animated" :class="open? 'zoomIn':''">
        <div class="title">
          {{title}}
          <div class="close" @click="cancel()"></div>
        </div>
        <div>
          <el-form label-width="240px">
            <el-form-item label="课程名称" :rules="[
      { required: true, message: ''}]">
              <el-input
                ref="libraryCourseName"
                style="width:50%;"
                clearable
                v-model="courseData.libraryCourseName"
                placeholder="请输入课程名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="科目" :rules="[
      { required: true, message: ''}]">
              <el-cascader
                ref="subjectId"
                style="width:50%;"
                :key="isResouceShow"
                v-model="selectSubjectId"
                :options="subjectList"
                placeholder="请选择科目"
              ></el-cascader>
              <el-button type="primary" style="padding:0.1rem 0.2rem;" @click="openAddSubject">新增科目</el-button>
            </el-form-item>
            <el-form-item label="资源存储渠道" :rules="[
      { required: true, message: ''}]">
              <el-select
                ref="storageChannel"
                style="width:50%;"
                :disabled="!courseData.editableOfStorageChannel"
                v-model="courseData.storageChannel"
                placeholder="请选择资源存储渠道"
              >
                <el-option
                  v-for="item in storageChannelList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="适用年龄" :rules="[
      { required: true, message: ''}]">
              <el-select
                ref="minSuitableAge"
                v-model="courseData.minSuitableAge"
                @change="ageStartChange()"
                style="width:24%;"
                clearable
                placeholder="开始年龄"
              >
                <el-option
                  v-for="item in ageStartList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                  v-show="item.show"
                ></el-option>
              </el-select>&nbsp;~
              <el-select
                ref="maxSuitableAge"
                v-model="courseData.maxSuitableAge"
                @change="ageEndChange()"
                clearable
                style="width:24%;"
                placeholder="结束年龄"
              >
                <el-option
                  v-for="item in ageEndList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                  v-show="item.show"
                ></el-option>
              </el-select>
              <!-- <el-input
                ref="suitableAge"
                style="width:50%;"
                maxlength="2"
                onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
                oninput="value=value.replace(/[^\d]/g,'')"
                v-model="courseData.suitableAge"
                placeholder="请输入适用年龄"
              >
                <template slot="append">岁</template>
              </el-input>-->
            </el-form-item>
            <el-form-item label="时长" :rules="[
      { required: true, message: ''}]">
              <el-input-number
                ref="oneSyllabusDuration"
                size="small"
                controls-position="right"
                class="newclassroomNumber"
                style="width:42%;"
                v-model="courseData.oneSyllabusDuration"
                :min="0"
                :max="999"
              ></el-input-number>&nbsp;分钟/节
              <!-- <el-input
                
                style="width:50%;"
                maxlength="3"
                
                onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
                oninput="value=value.replace(/[^\d]/g,'')"
                v-model="courseData.oneSyllabusDuration"
                placeholder="请输入时长"
              >
                <template slot="append">分钟/节</template>
              </el-input>-->
            </el-form-item>
            <el-form-item label="课节数" :rules="[
      { required: true, message: ''}]">
              <el-input-number
                ref="syllabusNum"
                size="small"
                controls-position="right"
                class="newclassroomNumber"
                style="width:47%;"
                v-model="courseData.syllabusNum"
                :min="num"
                :max="999"
                :step="num"
              ></el-input-number>&nbsp;节
              <!-- <el-input
                ref="syllabusNum"
                style="width:50%;"
                maxlength="3"
                :disabled="isDisable"
                onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
                oninput="value=value.replace(/[^\d]/g,'')"
                v-model="courseData.syllabusNum"
                placeholder="请输入课节数"
              >
                <template slot="append">节</template>
              </el-input>-->
            </el-form-item>
            <el-form-item label="名师上课:" v-if="courseData.feiboCoursePackageId != null">
              开课&nbsp;
              <el-input-number
                ref="tutionInterval"
                size="small"
                controls-position="right"
                class="newclassroomNumber"
                style="width:20%;"
                v-model="courseData.tutionInterval"
                :min="0"
                :max="courseData.oneSyllabusDuration"
              ></el-input-number>&nbsp;分钟开始上课
            </el-form-item>
          </el-form>
        </div>
        <div class="btn_div">
          <div class="btn_sure" @click="sure()">确 认</div>
          <div class="btn_cancel" @click="cancel()">取 消</div>
        </div>
      </div>
    </div>
    <el-dialog
      title="新建科目"
      :visible.sync="dialogFormVisible"
      center
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="subjectData">
        <el-form-item
          label="科目"
          :label-width="formLabelWidth"
          :rules="[
      { required: true, message: '科目不能为空'}]"
        >
          <el-input
            style="width:60%"
            maxlength="30"
            clearable
            v-model="subjectData.name"
            placeholder="请输入科目"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="子科目"
          :rules="[
      { required: true, message: ''}]"
          :label-width="formLabelWidth"
        >
          <el-tag
            :key="tag.subSubjectName"
            v-for="tag in subjectData.subSubjectList"
            closable
            :disable-transitions="false"
            @close="handleClose(tag,1)"
          >{{tag.subSubjectName}}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm(1)"
            @blur="handleInputConfirm(1)"
          ></el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput(1)">新增子科目</el-button>
        </el-form-item>
        <el-form-item
          label="序号"
          :label-width="formLabelWidth"
          :rules="[
      { required: true, message: '序号不能为空'}]"
        >
          <el-input-number
            size="small"
            controls-position="right"
            class="newclassroomNumber"
            style="width:60%;"
            v-model="subjectData.orderBy"
            :min="1"
            :max="9999"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :class="{disable:inputVisible}"
          @click="addCofim()"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
var vm, user;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      isAdd: false,
      isDisable: false,
      title: "",
      num: 1,
      courseData: {},
      dialogFormVisible: false,
      formLabelWidth: "140px",
      inputVisible: false,
      inputValue: "",
      subjectData: {
        name: "",
        orderBy: "",
        orgId: 0,
        subSubjectList: []
      },
      isResouceShow: 1,
      storageChannelList: [],
      selectSubjectId: [], //筛选科目的数组
      ageStartList: [], //筛选适用年龄数据
      ageEndList: [], //筛选适用年龄数据
      subjectList: [] //科目数据
    };
  },
  methods: {
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 50);
      vm.selectSubjectId = [];
      vm.num = 1;
      let dicdata = tool.getItem(lsKey.dict, true);
      vm.storageChannelList = dicdata["storage_channel"];
      console.log(vm.storageChannelList);
      if (data.libraryCourseId == undefined) {
        vm.title = "新增库课程";
        vm.isAdd = true;
        vm.courseData = {
          libraryCourseName: "",
          subjectId: "",
          minSuitableAge: "",
          maxSuitableAge: "",
          oneSyllabusDuration: "",
          syllabusNum: "",
          editableOfStorageChannel: true,
          storageChannel: ""
        };
      } else {
        vm.title = "编辑库课程";
        vm.isAdd = false;
        vm.courseData = data;
        vm.courseData.minSuitableAge = vm.courseData.minSuitableAge + "";
        vm.courseData.maxSuitableAge = vm.courseData.maxSuitableAge + "";
        console.log(data);
        vm.num =
          vm.courseData.feiboCoursePackageId != null
            ? vm.courseData.feiboSyllabusNum
            : 1;
        let cloneData = tool.clone(data);

        if (cloneData.subSubjectId == null) {
          if (cloneData.subjectId != null) {
            vm.selectSubjectId.push(cloneData.subjectId);
          } else {
            vm.selectSubjectId = [];
          }
        } else {
          vm.selectSubjectId.push(cloneData.subjectId);
          vm.selectSubjectId.push(cloneData.subSubjectId);
        }
      }
      vm.initData();
      // api
      //   .getcourseTypeList()
      //   .then(function(data) {
      //     //课程类型列表
      //     if (data.resultCode == 2000) {
      //       //当课程类型为双师时
      //       if (vm.courseData.courseType == 4) {
      //         vm.isDisable = true;
      //         data.list.push({
      //           dicValue: 4,
      //           name: "双师"
      //         });
      //       }
      //       vm.courseTypeList = data.list;
      //     } else {
      //       this.$message.error(data.message);
      //     }
      //     return
      //   })
    },
    openAddSubject() {
      vm.subjectData = {
        name: "",
        orderBy: "",
        orgId: 0,
        subSubjectList: []
      };
      vm.inputValue = "";
      vm.inputVisible = false;
      vm.dialogFormVisible = true;
    },
    initData() {
      let tempList = [];
      api
        .getSubjectList({
          orgId: user.orgId + ""
        })
        .then(function(data) {
          //枚举科目列表
          if (data.result == "操作成功") {
            data.list.forEach(item => {
              let subList = [];
              item.subSubjectList.forEach(r => {
                subList.push({
                  value: r.subSubjectId,
                  label: r.subSubjectName
                });
              });
              if (subList.length > 0) {
                tempList.push({
                  value: item.subjectId,
                  label: item.name,
                  children: subList
                });
              } else {
                tempList.push({
                  value: item.subjectId,
                  label: item.name
                });
              }
            });
            ++vm.isResouceShow;
            vm.subjectList = tempList;
          } else {
            this.$message.error(data.message);
          }
        });
    },
    /**
     * 向列表中添加数据
     */
    addCofim() {
      if (this.subjectData.name == "") {
        this.$message.warning("科目名称不能为空");
        return;
      }
      if (!tool.judge("classname", this.subjectData.name)) {
        this.$message.warning("请输入有效的科目名称");
        return;
      }
      if (this.subjectData.orderBy == "") {
        this.$message.warning("序号不能为空");
        return;
      }
      if (!tool.judge("integer0", this.subjectData.orderBy)) {
        this.$message.warning("序号需为正整数");
        return;
      }
      if (parseInt(this.subjectData.orderBy) > 999) {
        this.$message.warning("序号不能超过999");
        return;
      }

      if (this.subjectData.subSubjectList.length == 0) {
        this.$message.warning("请创建子科目！");
        return;
      }
      let paras = {
        name: this.subjectData.name,
        orgId: user.orgId,
        orderBy: this.subjectData.orderBy,
        subSubjectList: this.subjectData.subSubjectList
      };
      api.subjectAdd(paras).then(function(data) {
        if (data.resultCode == 2000) {
          vm.dialogFormVisible = false;
          vm.subjectData = {
            name: "",
            orderBy: "",
            subSubjectList: [],
            orgId: user.orgId
          };
          vm.initData();
          vm.$message({
            message: "添加科目成功",
            type: "success"
          });
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    handleClose(tag, val) {
      if (val == 1) {
        this.subjectData.subSubjectList.splice(
          this.subjectData.subSubjectList.indexOf(tag),
          1
        );
      } else {
        this.subjectData.subSubjectList.splice(
          this.subjectData.subSubjectList.indexOf(tag),
          1
        );
      }
    },
    showInput(val) {
      this.inputVisible = true;
      this.$nextTick(_ => {
        if (val == 1) {
          this.$refs.saveTagInput.$refs.input.focus();
        } else {
          this.$refs.saveTagInput_update.$refs.input.focus();
        }
      });
    },
    handleInputConfirm(val) {
      let inputValue = this.inputValue;
      if (!inputValue) return;
      if (tool.judge("name", inputValue)) {
        if (val == 1) {
          this.subjectData.subSubjectList.push({ subSubjectName: inputValue });
        } else {
          this.subjectData.subSubjectList.push({ subSubjectName: inputValue });
        }
        this.inputVisible = false;
        this.inputValue = "";
      } else {
        this.$message.warning("请输入有效的子科目名称");
        this.inputValue = "";
        if (val == 1) {
          this.$refs.saveTagInput.$refs.input.focus();
        } else {
          this.$refs.saveTagInput_update.$refs.input.focus();
        }
        return;
      }
    },
    ageStartChange: function() {
      //开始年龄发生改变
      //限制结束年龄
      vm.ageEndList.forEach(function(item) {
        if (
          !vm.courseData.minSuitableAge ||
          parseInt(item.value) >= parseInt(vm.courseData.minSuitableAge)
        ) {
          item.show = true;
        } else {
          item.show = false;
        }
      });

      // var age = (vm.ageStart || -1) + "/" + (vm.ageEnd || -1);
    },
    ageEndChange: function() {
      //结束年龄发生改变
      //限制开始年龄
      vm.ageStartList.forEach(function(item) {
        if (
          !vm.courseData.maxSuitableAge ||
          parseInt(item.value) <= parseInt(vm.courseData.maxSuitableAge)
        ) {
          item.show = true;
        } else {
          item.show = false;
        }
      });

      // var age = (vm.ageStart || -1) + "/" + (vm.ageEnd || -1);
    },

    sure: function() {
      var rules = [];
      let libraryCourseName = this.$refs.libraryCourseName;
      let subjectId = this.$refs.subjectId;
      let minSuitableAge = this.$refs.minSuitableAge;
      let maxSuitableAge = this.$refs.maxSuitableAge;
      let oneSyllabusDuration = this.$refs.oneSyllabusDuration;
      let syllabusNum = this.$refs.syllabusNum;
      let storageChannel = this.$refs.storageChannel;
      rules.push({
        judge: tool.judge("courseName", vm.courseData.libraryCourseName),
        focus: libraryCourseName,
        tips: "请输入正确的课程名称"
      });
      console.log(vm.selectSubjectId);
      rules.push({
        judge: vm.selectSubjectId.length != 0,
        focus: null,
        tips: "请输入科目"
      });
      rules.push({
        judge: vm.courseData.storageChannel,
        focus: storageChannel,
        tips: "请输入资源存储渠道"
      });
      rules.push({
        judge: vm.courseData.minSuitableAge != "",
        focus: minSuitableAge,
        tips: "请选择开始年龄"
      });
      rules.push({
        judge: vm.courseData.maxSuitableAge != "",
        focus: maxSuitableAge,
        tips: "请选择结束年龄"
      });
      rules.push({
        judge: vm.courseData.oneSyllabusDuration,
        focus: oneSyllabusDuration,
        tips: "请输入时长"
      });
      rules.push({
        judge: vm.courseData.syllabusNum && vm.courseData.syllabusNum >= 1,
        focus: syllabusNum,
        tips: "请输入课节数并且不小于1"
      });
      if (!tool.validate(rules)) {
        return;
      }
      let index = vm.selectSubjectId.length;
      if (index > 1) {
        vm.courseData.subSubjectId = vm.selectSubjectId[1];
        vm.courseData.subjectId = vm.selectSubjectId[0];
      } else {
        vm.courseData.subjectId = vm.selectSubjectId[0];
      }
      vm.courseData._wait = "";
      if (vm.isAdd) {
        api.libraryCourseAdd(vm.courseData).then(function(data) {
          if (data.resultCode == 2000) {
            vm.$message({
              message: "添加成功",
              type: "success"
            });
            vm.$emit("callback", "添加成功");
            vm.cancel();
          } else {
            vm.$message.error(data.message);
          }
        });
      } else {
        vm.courseData.createTime = null;
        api.libraryCourseUpdate(vm.courseData).then(function(data) {
          if (data.resultCode == 2000) {
            vm.$message({
              message: "编辑成功",
              type: "success"
            });
            vm.$emit("callback", "添加成功");
            vm.cancel();
          } else {
            vm.$message.error(data.message);
          }
        });
      }
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.isDisable = false;
        vm.courseData = {};
      }, 500);
    }
  },
  created: function() {
    vm = this;
    //获取数据字典
    let dicdata = tool.getItem(lsKey.dict, true);
    user = tool.getItem(lsKey.user, true); //得到当前用户信息
    for (let i = 0; i < 100; i++) {
      vm.ageStartList.push({ name: "" + i, value: "" + i, show: true });
      vm.ageEndList.push({ name: "" + i, value: "" + i, show: true });
    }
  }
};
</script>
<style lang="scss">
.newCourseContainer {
  .disable {
    pointer-events: none;
  }
  .line_from {
    height: 1px;
    margin: 0.24rem 0.18rem 0.18rem 0.18rem;
    background-color: #f3f6fc;
  }
  .el-form--inline .el-form-item {
    vertical-align: inherit;
  }
  .el-form-item__content {
    font-size: 0.16rem;
  }
  .el-input__inner {
    border-radius: 0.08rem;
    font-size: 0.16rem;
    color: #666666;
    height: 0.36rem;
    line-height: 0.36rem;
  }
  .el-input__icon {
    line-height: 0.36rem;
  }
  .el-input-group__append,
  .el-input-group__prepend {
    background-color: #ffffff;
    color: #666666;
    border: 0rem solid #ffffff;
    font-size: 0.16rem;
    padding: 0 0.1rem;
  }
  .el-radio {
    margin-right: 0.1rem;
  }
  .el-form-item__label {
    font-size: 0.16rem;
    color: #666666;
  }

  .input_search {
    .el-input__inner {
      background-color: rgb(247, 248, 250);
    }
  }
  .newclassroomNumber {
    .el-input__inner {
      border-radius: 0.04rem !important;
    }
  }
  .el-tag:first-child {
    margin-right: 10px;
  }
  .el-tag {
    font-size: 0.16rem;
  }
  .el-tag + .el-tag {
    margin-right: 10px;
  }
  .button-new-tag {
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    vertical-align: bottom;
  }
}
</style>
<style scoped src="@/style/module/dialog.css"></style>
<style scoped>
.panel {
  width: 10rem;
}
</style>

